package com.hctg.forced2sleep.dialog;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import com.actor.myandroidframework.action.AnimAction;
import com.actor.myandroidframework.fragment.BaseDialogFragment;
import com.actor.myandroidframework.utils.LogUtils;
import com.actor.myandroidframework.utils.TextUtils2;
import com.actor.myandroidframework.utils.toaster.ToasterUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.ImageUtils;
import com.blankj.utilcode.util.RomUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.bumptech.glide.Glide;
import com.hctg.forced2sleep.R;
import com.hctg.forced2sleep.activity.WallpaperActivity;
import com.hctg.forced2sleep.adapter.PermissionListDialogAdapter;
import com.hctg.forced2sleep.bean.MineItem;
import com.hctg.forced2sleep.databinding.DialogPermissionListBinding;
import com.hctg.forced2sleep.service.MyAccessibilityService;
import com.hctg.forced2sleep.service.MyWallpaperService;
import com.hctg.forced2sleep.utils.AccessibilityUtils;
import com.hctg.forced2sleep.utils.BatteryUtils;
import com.hctg.forced2sleep.utils.UsageStatsUtils;
import com.hctg.forced2sleep.utils.WallpaperUtils;
import com.hctg.forced2sleep.utils.WhiteListUtils;
import com.hjq.permissions.OnPermissionCallback;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;

import java.io.File;
import java.util.List;

/**
 * description: 首页权限弹框
 * company    :
 *
 * @author : ldf
 * date       : 2024/6/10 on 21
 * @version 1.0
 */
public class PermissionListDialog extends BaseDialogFragment {

    private DialogPermissionListBinding viewBinding;
    private PermissionListDialogAdapter mAdapter1, mAdapter2;

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setWidthPercent(0.888888f, SizeUtils.dp2px(308f));
        setGravityAndAnimation(Gravity.CENTER, AnimAction.ANIM_RIGHT_SLIDE);
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        viewBinding = DialogPermissionListBinding.inflate(inflater, container, false);
        return viewBinding.getRoot();
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        viewBinding.btnClose.setOnClickListener(v -> { dismissAllowingStateLoss(); });
        viewBinding.tvTitle.setText(RomUtils.getRomInfo().getName() + "权限加固");
        viewBinding.tvVersion.setText(TextUtils2.getStringFormat("%s (%d)", AppUtils.getAppVersionName(), AppUtils.getAppVersionCode()));

        mAdapter1 = new PermissionListDialogAdapter();
        mAdapter1.addData(new MineItem(0, R.drawable.permission_accessbility, "无障碍锁机"));
        mAdapter1.addData(new MineItem(1, R.drawable.permission_wallpaper, "壁纸守护(推荐)"));
        mAdapter1.addData(new MineItem(2, R.drawable.permission_power, "应用使用情况"));
        mAdapter1.getItem(0).visible = false;    //显示第2行内容
        mAdapter1.getItem(0).subName = "遮盖全屏，实现禅定效果";
        mAdapter1.getItem(1).subName = "App运行更加稳定，防清理失效";
        mAdapter1.getItem(2).subName = "应用监督、白名单需要开启";

        mAdapter2 = new PermissionListDialogAdapter();
        mAdapter2.addData(new MineItem(0, R.drawable.permission_float, "悬浮窗权限"));
        mAdapter2.addData(new MineItem(1, R.drawable.permission_autorun, "自启动权限(定时必选)"));
        mAdapter2.addData(new MineItem(2, R.drawable.permission_power, "后台保活(防闪退)"));
        mAdapter2.addData(new MineItem(3, R.drawable.permission_notification, "锁机时消息屏蔽"));
        mAdapter2.getItem(0).subName = "用于加固禅定空间";
        mAdapter2.getItem(1).subName = "用于防止后台自动关闭、闪退";
        mAdapter2.getItem(2).subName = "在省电模式下防止自动关闭";
        mAdapter2.getItem(3).subName = "实现可接电话，可统计屏蔽通知数";

        viewBinding.recyclerView1.setAdapter(mAdapter1);
        viewBinding.recyclerView2.setAdapter(mAdapter2);

        mAdapter1.setOnItemClickListener((adapter, view1, position) -> {
            switch (position) {
                case 0: //无障碍锁机
                    new AccessibilityOpenTipsDialog(mActivity).setAcceptClickListener(v -> {
                        AccessibilityUtils.go2AccessibilitySetting(mActivity, position);
                    }).show();
                    break;
                case 1: //壁纸守护
                    boolean isGradient = WallpaperUtils.isWallpaperServiceOpened(MyWallpaperService.class);
                    if (isGradient) {
                        startActivity(new Intent(mActivity, WallpaperActivity.class));
                    } else {
                        getWallpaperPermission();
                    }
                    break;
                case 2: //应用使用情况
                    if (!UsageStatsUtils.isGranted(mActivity)) {
                        UsageStatsUtils.requestUsageStats(mActivity, (permissions, allGranted) -> {
                            refreshPermissionState();
//                            UsageStatsUtils.go2Setting(mActivity);
                        });
                    }
                    break;
                default:
                    break;
            }
        });

        mAdapter2.setOnItemClickListener((adapter, view1, position) -> {
            switch (position) {
                case 0: //悬浮窗权限
                    if (!XXPermissions.isGranted(mActivity, Permission.SYSTEM_ALERT_WINDOW)) {
                        XXPermissions.with(mActivity)
                                .permission(Permission.SYSTEM_ALERT_WINDOW)
                                .request((permissions, allGranted) -> {
                                    refreshPermissionState();
                                });
                    }
                    break;
                case 1: //自启动权限, 开机启动
//                    ToasterUtils.warning("开机启动(未完成,需自己开启)");
                    boolean success = WhiteListUtils.gotoLaunchList(mActivity);
                    if (!success) {
//                        ActivityUtils.startLauncherActivity("com.iqoo.secure");//打开i管家
//                        AppUtils.launchApp("com.iqoo.secure");
                    }
                    break;
                case 2: //后台保活(防闪退), 忽略电池优化
                    if (!BatteryUtils.isIgnoringBatteryOptimizations(mActivity)) {
                        BatteryUtils.requestIgnoreBatteryOptimizations(mActivity, (permissions, allGranted) -> {
                            refreshPermissionState();
                        });
                    }
                    break;
                case 3: //锁机时消息屏蔽 (实现可接电话，可统计屏蔽通知数)
                    XXPermissions.startPermissionActivity(mActivity, Permission.BIND_NOTIFICATION_LISTENER_SERVICE);
                    break;
                default:
                    break;
            }
        });
    }

    @Override
    public void onResume() {
        super.onResume();
        LogUtils.error("onResume");
        refreshPermissionState();
    }

    private void refreshPermissionState() {
        //无障碍
        mAdapter1.getItem(0).hasPermission = AccessibilityUtils.isAccessibilitySettingsOn(MyAccessibilityService.class);
        //壁纸
        mAdapter1.getItem(1).hasPermission = WallpaperUtils.isWallpaperServiceOpened(MyWallpaperService.class);
        //应用使用情况
        mAdapter1.getItem(2).hasPermission = UsageStatsUtils.isGranted(mActivity);

        //悬浮窗权限
        mAdapter2.getItem(0).hasPermission = XXPermissions.isGranted(mActivity, Permission.SYSTEM_ALERT_WINDOW);
        //自启动权限(定时必选)
        mAdapter2.getItem(1).hasPermission = false;
        //后台保活(防闪退), 电池优化
        mAdapter2.getItem(2).hasPermission = BatteryUtils.isIgnoringBatteryOptimizations(mActivity);
        //锁机时消息屏蔽           //通知使用权
        mAdapter2.getItem(3).hasPermission = XXPermissions.isGranted(mActivity, Permission.BIND_NOTIFICATION_LISTENER_SERVICE);

        mAdapter1.notifyDataSetChanged();
        mAdapter2.notifyDataSetChanged();
    }

    private void getWallpaperPermission() {
        if (XXPermissions.isGranted(mActivity, Permission.READ_EXTERNAL_STORAGE)) {
            getWallpaperAndSet();
        } else {
            XXPermissions.with(mFragment)
                    .permission(Permission.READ_EXTERNAL_STORAGE)
                    .request(new OnPermissionCallback() {
                        @Override
                        public void onGranted(@NonNull List<String> permissions, boolean allGranted) {
                            getWallpaperAndSet();
                        }
                        @Override
                        public void onDenied(@NonNull List<String> permissions, boolean doNotAskAgain) {
                            OnPermissionCallback.super.onDenied(permissions, doNotAskAgain);
                            ToasterUtils.warning("您拒绝了权限, 获取壁纸失败!");
                        }
                    });
        }
    }

    private void getWallpaperAndSet() {
        @SuppressLint("MissingPermission")
        Drawable wallpaperDesktop = WallpaperUtils.getWallpaperDesktop(mActivity);
        Glide.with(this)
                .load(wallpaperDesktop)
                .into(viewBinding.qqgroup);
        Bitmap bitmap = ImageUtils.drawable2Bitmap(wallpaperDesktop);
        if (bitmap != null) {
            File file = ImageUtils.save2Album(bitmap, Bitmap.CompressFormat.PNG);
            if (file != null) {
                WallpaperUtils.setPictureWallPaper(mActivity, file.getAbsolutePath(), MyWallpaperService.class);
            }
        }
    }
}
